<template>
  <el-dialog v-model="pickRangeDialog" title="预定时间选择" width="700"
             style="display: flex;flex-direction: column;align-items: center">
    <!--    <div style="margin-top: 20px">-->
    <!--      <a style="color: darkred">* 不可选的日期为已被预约的日期</a>-->
    <!--    </div>-->
    <div style="display: flex;flex-direction: column; margin-top: 20px">
      <div style="font-weight: bold;color: orangered">已被预约的时间段(已被预约的时间段不可再预约)：</div>
      <div>
        <!--        disabledDates-->
        <div v-for="(value, key) in disabledDates" :key="key" style="width: 100%">
          <el-tag size="large" type="danger" style="margin-top: 10px;font-size: 16px;">
            {{ formatISODateToYMDHM(value.start) + '  -到-  ' + formatISODateToYMDHM(value.end) }}
          </el-tag>
        </div>

      </div>
    </div>
    <div class="demo-datetime-picker" style="margin-top: 20px">
      <div class="block">
        <el-date-picker
            v-model="timeRange"
            size="large"
            type="datetimerange"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            format="YYYY-MM-DD HH"
            date-format="YYYY/MM/DD ddd"
            time-format="A hh"
        />
      </div>
    </div>
    <div class="btn-div">
      <el-button style="margin-top: 20px" type="primary" @click="bookingSubmitClick">预约提交</el-button>
    </div>
  </el-dialog>


  <div style="display: flex;flex-direction: column; width: 100%">
    <div
        style="display: flex;flex-direction: row;align-items: center;justify-content: space-between;width: 100%;height: 65px;background: #97a8be">
      <div
          style="display: flex;flex-direction: row;margin-left: 30px;align-items: center;font-weight: bold;font-size: 22px">
        <el-image src="/image/booking-icon.png" style="width: 40px;height: 40px"></el-image>
        <a style="margin-left: 20px">预定系统</a>
      </div>
      <div style="margin-right: 30px">
        <el-button @click="quitClick">{{ '您好,' + store.getters.uname }}</el-button>
      </div>
    </div>

    <el-tabs v-model="activeName" type="border-card" class="demo-tabs" @tab-click="handleClick"
             style="margin-top: 25px;margin-left: 20px;margin-right: 20px">
      <el-tab-pane label="预约设备" name="first">
        <div style="display: flex;flex-direction: column;width: 100%">
          <div v-for="(value, key) in listData" :key="key" style="width: 100%">
            <el-card style="max-width: 100%;margin-top: 5px;margin-left: 20px;margin-right: 20px" shadow="hover">
              <template #header>
                <div style="display: flex;flex-direction: row;align-items: center">
                  <div style="display: flex;flex-direction: row;align-items: center">
                    <a class="a-title">设备名称：</a>
                    <a>{{ value.name }}</a>
                  </div>

                  <div style="display: flex;flex-direction: row;align-items: center;margin-left: 50px">
                    <a class="a-title">设备编号：</a>
                    <a>{{ value.code }}</a>
                  </div>

                  <div style="display: flex;flex-direction: row;align-items: center;margin-left: 50px">
                    <a class="a-title">设备型号：</a>
                    <a>{{ value.type }}</a>
                  </div>

                  <div style="display: flex;flex-direction: row;align-items: center;margin-left: 50px">
                    <a class="a-title">设备状态：</a>
                    <el-tag type="primary" size="large" v-show="value.status === '0'">正常-可预约</el-tag>
                    <el-tag type="danger" size="large" v-show="value.status === '1'">维修-不可预约</el-tag>
                  </div>
                </div>
              </template>
              <div style="display: flex; flex-direction: row; align-items: center; width: 100%">
                <div v-for="(pic, key) in JSON.parse(value.pic)" :key="key" style="width: 19%">
                  <el-image :src="pic.url" style="width: 90%;"/>
                </div>
              </div>


              <template #footer>
                <div style="display: flex;flex-direction: row;align-items: center;justify-content: space-between">
                  <div style="display: flex;flex-direction: row;align-items: center">
                  </div>
                  <el-button :type="value.status === '1'? 'info':'primary'" :disabled="value.status === '1'"
                             @click="bookingClick(value)">预约此设备
                  </el-button>
                </div>

              </template>
            </el-card>
          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane label="我的预约" name="second">
        <el-table :data="tableData" border style="width: 100%;margin-left: 20px">
<!--          <el-table-column prop="bId" label="设备ID" width="90"/>-->
          <el-table-column prop="mname" label="设备名称" width="180"/>
          <el-table-column prop="mcode" label="设备编号" width="120"/>
          <el-table-column prop="start" label="预约开始时间" width="150">
            <template #default='{row}'>
              {{ formatDateToYYYYMMDD(row.start) }}
            </template>
          </el-table-column>
          <el-table-column prop="end" label="预约结束时间" width="150">
            <template #default='{row}'>
              {{ formatDateToYYYYMMDD(row.end) }}
            </template>
          </el-table-column>
          <el-table-column prop="uname" label="预约人" width="150"/>
          <el-table-column prop="status" label="设备状态" width="130">
            <template #default='{row}'>
              <el-tag type="primary" v-show="row.eStatus === '0'">正常-可预约</el-tag>
              <el-tag type="danger" v-show="row.eStatus === '1'">维修-不可预约</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="bStatus" label="预约状态" width="180">
            <template #default='{row}'>
              <el-tag type="info" v-show="row.bStatus === 0">待审核</el-tag>
              <el-tag type="success" v-show="row.bStatus === 1">通过</el-tag>
              <el-tag type="danger" v-show="row.bStatus === 2">拒绝</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="memo" label="拒绝理由" width="150"/>
          <el-table-column
              label='模块操作'
              fixed='right'
              width='200'
              align='center'
          >
            <template #default='{row}'>
              <el-button
                  type='danger'
                  size='small'
                  @click='callBack(row)'
              >撤回预约
              </el-button
              >
            </template>
          </el-table-column>

        </el-table>
        <el-pagination
            class='pagination'
            @size-change='handleSizeChange'
            @current-change='handleCurrentChange'
            :current-page='page'
            :page-size='size'
            :page-sizes='[5, 10, 20]'
            layout='total, sizes, prev, pager, next, jumper'
            :total='total'
        >
        </el-pagination>
      </el-tab-pane>
    </el-tabs>



  </div>
</template>

<script setup>

import {ref, onMounted, computed, onBeforeUpdate, watch, reactive} from 'vue'
import {useStore} from 'vuex'
import {listEquipments} from "@/api/equipment";
import {bookingAdd, checkRange, delBookingById, listHisByMid, listMyBookingList} from "@/api/booking";
import {checkT} from "@/api/sys";


const store = useStore()

const userName = ref('')

const tableData = ref([])
const page = ref(1) // 页数
const size = ref(10)// 页面数
const total = ref(0) // 总数

// 设备使用人预约系统时显示：
// 设备状态
// 设备编号
// 设备名称
// 设备型号
// 设备图片
const listData = ref([])
const pickRangeDialog = ref(false) //选择时间范围弹窗
const timeRange = ref([])
const startT = ref('')
const endT = ref('')
const uId = ref(0)
const nowId = ref(0)
const disabledDates = ref([])
const activeName = ref('first')
const nowRowId = ref(0)

const value1 = ref('')
const valueRange = ref('')


onMounted(() => {
  console.log('onMounted')
  initEquipmentData()  //获取待预约的列表
  list(page.value, size.value) //获取自己预约的列表
  checkToken() //检测token是否过期
})


const checkToken = async () => {
  if (store.getters.token !== '') {
    const result = await checkT({
      token: store.getters.token
    })

    console.log('checkT = ', result)
    if (result.is_valid) {
    } else {
      //token无效
      await store.dispatch('user/logout')
    }
  }
}


//初始化数据
const list = async (page, pagesize) => {
  let data = await listMyBookingList({
    uid: store.getters.uid, //用户id
    page,
    pagesize
  })
  console.log('listBookingList=   ', data)
  tableData.value = data.msg.data
  total.value = data.msg.total
}


const handleSizeChange = (currentSize) => {
  size.value = currentSize
  list(page.value, size.value)
}

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  page.value = currentPage
  list(page.value, size.value)
}


// 设备名称
// 设备编号
// 预约人
// 开始时间
// 结束时间
// 审核状态

const callBack = (row) => {
  console.log(row)
  console.log(row.bId)
  ElMessageBox.confirm(
      '是否撤销预约?撤销后不可恢复',
      'Warning',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then(async () => {
        const result = await delBookingById({
          id: row.bId
        })
        //console.log('del-result = ', result)
        if (result.error_code === 0) {
          ElMessage({
            message: '撤回成功',
            type: 'success'
          })
          await list() //获取自己预约的列表
        }
      })
      .catch(() => {
        // ElMessage({
        //   type: 'info',
        //   message: 'Delete canceled',
        // })
      })
}


function formatDateToYYYYMMDD(isoString) {
  // 使用Date构造函数来解析ISO 8601格式的日期字符串
  const date = new Date(isoString);

  // 检查日期是否有效
  if (isNaN(date.getTime())) {
    throw new Error('Invalid date string');
  }

  // 获取年月日的部分，并使用padStart方法确保月份和日期始终是两位数
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // getMonth返回的是0-11，所以需要+1
  const day = String(date.getDate()).padStart(2, '0');

  // 拼接年月日并返回
  return `${year}-${month}-${day}`;
}

function formatISODateToYMDHM(isoDateString) {
  // 创建一个 Date 对象
  const date = new Date(isoDateString);

  // 验证日期是否有效
  if (isNaN(date.getTime())) {
    throw new Error('Invalid ISO date string');
  }

  // 获取年月日时分
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从 0 开始的，所以需要 +1
  const day = String(date.getDate()).padStart(2, '0');
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');

  // 拼接成字符串
  return `${year}-${month}-${day} ${hours}:${minutes}`;
}


const handleClick = (tab, event) => {
  console.log(tab, event)
}


const checkRangeByMid = async (mid) => {
  let result = await listHisByMid({
    mid,
  })
  disabledDates.value = result.msg
  console.log('根据Mid查询的返回= ', result)
}

//拿到设备列表
const initEquipmentData = async () => {
  const res = await listEquipments({})
  console.log('设备列表查询的返回： ', res)
  listData.value = res.msg.data
}

const bookingClick = (val) => {
  console.log('预订点击传入', val)
  nowId.value = val.id
  checkRangeByMid(nowId.value)
  pickRangeDialog.value = true
}

const bookingSubmitClick = async () => {
  startT.value = timeRange.value[0]
  endT.value = timeRange.value[1]

  console.log('timeRange.value', timeRange.value)

  if (timeRange.value === null || timeRange.value === '' || timeRange.value.length < 1) {
    ElNotification({
      title: 'Warning',
      message: '请选择时间范围',
      type: 'warning',
      duration: 2000,
    })
  } else {
    let data = await checkRange({
      mid: nowId.value,
      stime: timeRange.value[0],
      etime: timeRange.value[1],
    })
    console.log('提交后验证后的反馈：   ', data.msg)
    if (data.msg === true) {
      console.log('有重叠的时间')
      ElNotification({
        title: 'Warning',
        message: '所选时间段已被预约，请换一个时间段',
        type: 'warning',
        duration: 2000,
      })
    } else {
      console.log('无重叠的时间，可以提交')
      let result = await bookingAdd({
        uid: store.getters.uid, //用户id
        mid: nowId.value,  //设备id
        start: startT.value,//预约的开始时间
        end: endT.value, //预约的结束时间
        status: 0,
      })

      if (result.error_code === 0) {
        ElNotification({
          title: 'Success',
          message: '预约提交成功',
          type: 'success',
          duration: 1000,
          onClose: () => {
            pickRangeDialog.value = false
            timeRange.value = ''
            disabledDates.value = []
          }
        })
      } else {
      }
    }
  }
}

const timeRangeChange = (val) => {
  console.log('change')
  // 确保选择了两个日期
  if (val && val.length === 2) {
    const startDate = new Date(val[0]);
    const endDate = new Date(val[1]);
    // 检查两个日期之间是否超过30天
    if (endDate - startDate > 2592000000) {
      ElNotification({
        title: 'Warning',
        message: '选择的时间超过了一个月，请重新选择',
        type: 'warning',
        duration: 3000,
      })
      timeRange.value = ''
    }
  }
}


// 计算属性，因为disabledDates需要用在计算属性中
// const disabledDates = computed(() => {
//   // 将字符串转换为Date对象
//   return disabledDates.value.map(dateStr => {
//     return new Date(dateStr)
//   })
// })

// el-date-picker的disabledDate函数
// 计算当前选中日期是否在不可选日期范围内
// const isDateDisabled = (time) => {
//   // 将时间戳转换为日期对象
//   const date = new Date(time);
//   const startDate = new Date(disabledDates.value[0].start);
//   const endDate = new Date(disabledDates.value[0].end);
//
//   // 检查选中日期是否在某个不可选日期范围内
//   for (const disabledDate of disabledDates.value) {
//     const disabledStart = new Date(disabledDate.start);
//     const disabledEnd = new Date(disabledDate.end);
//
//     if (date >= disabledStart && date <= disabledEnd) {
//       return true;
//     }
//   }
//
//   return false;
// };


const quitClick = () => {
  ElMessageBox.alert('是否退出登陆', '退出登陆', {
    confirmButtonText: 'OK',
    cancelButtonText: 'Cancel'
  })
      .then(async ({value}) => {
        store.dispatch('user/logout')
      })
      .catch(() => {
      })
}


</script>


<style scoped>
.a-title {
  font-weight: bold;
}

.demo-date-picker {
  display: flex;
  width: 100%;
  padding: 0;
  flex-wrap: wrap;
}

.demo-date-picker .block {
  padding: 30px 0;
  text-align: center;
  border-right: solid 1px var(--el-border-color);
  flex: 1;
}

.demo-date-picker .block:last-child {
  border-right: none;
}

.demo-date-picker .demonstration {
  display: block;
  color: var(--el-text-color-secondary);
  font-size: 14px;
  margin-bottom: 20px;
}

.btn-div {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: center;
}


::v-deep .el-tabs__item {
  color: black;
  opacity: 0.9;
  font-size: 20px;
  font-weight: bold;
  margin-left: 20px;
}

/*去下划线 */
::v-deep .el-tabs__nav-wrap::after {
  position: static !important;
}

/* 下划线颜色 */
::v-deep .el-tabs__active-bar {
  background-color: red;
}


.pagination {
  margin-top: 15px;
  margin-left: 20px;
}


</style>
